import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:flutter/material.dart';

import 'const_config.dart';
import 'eventbus.dart';
import 'location.dart';
import 'utils.dart';

class MainPage extends StatefulWidget {
  const MainPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _MainPageState();
  }
}

class _MainPageState extends State<MainPage> with AmapLocation {
  final Map<String, Polyline> _polylines = <String, Polyline>{};
  final Map<String, Marker> _markers = <String, Marker>{};
  final Storage _storage = Storage();
  int count = 0;
  final List _list = [];
  late AMapController _controller;

  void sda(data) async {
    if(data == null) {
      return;
    }
    String name = data['name'];
    int type = data['type'];
    List<LatLng> ll = await _createPoints(name,type);
    drawLine(ll);
  }
  void drawLine(List<LatLng> ll){
    final Polyline polyline = Polyline(
        color: Colors.red,
        width: 2,
        joinType: JoinType.round,
        points: ll);
    LatLng _markerPosition = ll.first;
    LatLng _markerPositions = ll.last;
    final Marker marker = Marker(
      position: _markerPosition,
      icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueAzure),
    );
    final Marker marker1 = Marker(
      position: _markerPositions,
      icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueBlue),
    );
    setState(() {
      _polylines['1'] = polyline;
      _markers['2'] = marker;
      _markers['3'] = marker1;
    });
  }

  void _onMapCreated(AMapController controller) {
    _controller = controller;
  }

  void _changeCameraPosition(LatLng latLng) {
    _controller.moveCamera(
      CameraUpdate.newCameraPosition(
          CameraPosition(target: latLng, zoom: ConstConfig.MapZoom)),
      animated: true,
    );
  }

  @override
  void locationCallBack() {
    if (locationResult != null) {
      var lat = locationResult!['latitude'];
      var lng = locationResult!['longitude'];
      LatLng _markerPosition;
      if (lat is String && lng is String) {
        lat = double.parse(lat);
        lng = double.parse(lng);
      }
      _markerPosition = LatLng(lat as double, lng as double);
      if (onceLocation) {
        _changeCameraPosition(_markerPosition);
        final Marker marker = Marker(
          position: _markerPosition,
          icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueRed),
        );
        setState(() {
          _markers[marker.id] = marker;
        });
      } else {
        //测试脚本
        // double lats = lat * 1000000;
        // lats += 1000*count++;
        // lats = lats/1000000;
        _list.add("$lng,$lat");
        if (_list.length == 10) {
          _storage.writeCounter(_list.join(' '));
          _list.clear();
        }
      }
    }
  }

  Future<List<LatLng>> _createPoints(name,type) async {
    final List<LatLng> points = await Utils.getTrack("$name.${type==0?'txt':'json'}", type);
    _changeCameraPosition(Utils.calcZoom(points));
    return points;
  }


  @override
  void initState() {
    super.initState();
    bus.on("forLineName", (data) {
      sda(data);
    });
    bus.on('drawLine', (arg) async {
      if (arg == 1) {
        List<LatLng> ll = await Utils.getMyLine();
        _changeCameraPosition(Utils.calcZoom(ll));
        drawLine(ll);
      }
    });
    bus.on("onTrack", (data) {
      onceLocation = !data;
      if(data){
        startLocation();
      }else{
        stopLocation();
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    bus.off("forLineName");
    bus.off("onTrack");
    bus.off("drawLine");
  }

  @override
  Widget build(BuildContext context) {
    final AMapWidget map = AMapWidget(
      mapType: MapType.satellite,
      privacyStatement: ConstConfig.amapPrivacyStatement,
      buildingsEnabled: false,
      labelsEnabled: true,
      initialCameraPosition: const CameraPosition(
          target: ConstConfig.MapStart, zoom: ConstConfig.MapZoom),
      polylines: Set<Polyline>.of(_polylines.values),
      markers: Set<Marker>.of(_markers.values),
      onMapCreated: _onMapCreated,
    );
    return Scaffold(
      backgroundColor: Colors.white,
      body: Stack(
        children: [
          SizedBox(
            height: MediaQuery.of(context).size.height,
            width: MediaQuery.of(context).size.width,
            child: map,
          ),
          Align(
              alignment: Alignment.bottomLeft,
              child: Padding(
                  padding: const EdgeInsets.fromLTRB(12, 0, 0, 44),
                  child: Material(
                    color: Colors.transparent,
                    child: InkResponse(
                      splashColor: Colors.red,
                      containedInkWell: true,
                      child: IconButton(
                        icon: const Icon(
                          Icons.my_location_rounded,
                          size: 28,
                          color: Colors.white,
                        ),
                        onPressed: () {
                          startLocation();
                        },
                      ),),
                  )
              ))
        ],
      ),
    );
  }
}
